import { asyncRoutes, constantRoutes } from '@/router'

/**
 *使用roles.aCode判断当前用户是否具有权限的角色
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  try {
    // 有meta但不匹配aCode则没有权限
    if (route.meta.aCode) {
      return roles.some(role => {
        return route.meta.aCode == role.aCode
      })
    } else {
      return false
    }
  } catch (e) {
    console.log(e)
    return false
    // TODO handle the exception
  }
}

/**
 *通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param角色
 **/
export function filterAsyncRoutes(routes, roles) {
  const res = []
  try {
    routes.forEach(route => {
      const tmp = { ...route }
      // 无论父级子集  先进判断
      if (hasPermission(roles, tmp)) {
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
        res.push(tmp)
      }
    })
    return res
  } catch (e) {
    return []
    // TODO handle the exception
  }
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
